package com.cqeec.myblog.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.cqeec.myblog.model.Blogger;
import com.cqeec.myblog.service.BloggerService;
import com.cqeec.myblog.service.BloggerServiceImpl;

@WebServlet("/signin.html")
public class CheckUserServlet extends HttpServlet {
	private static final long serialVersionUID = 9201394973118140110L;

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		// 接收用户输入的账号和密码
		String username = request.getParameter("username");
		// 后端验证
		// 验证账号(是否输入)
		if (username == null || "".equals(username)) {
			// 未输入用户名
			request.setAttribute("message", "请输入账号！");
			request.getRequestDispatcher("login.html").forward(request, response);
			return;
		}
		String password = request.getParameter("password");
		// 验证密码(是否输入)
		if (password == null || "".equals(password)) {
			// 未输入用户名
			request.setAttribute("username", username);
			request.setAttribute("message", "请输入密码！");
			request.getRequestDispatcher("login.html").forward(request, response);
			return;
		}
		// 验证验证码
		String captcha = request.getParameter("captcha");
		// 验证验证码是否输入
		if (captcha == null || "".equals(captcha)) {
			// 未输入验证码
			request.setAttribute("username", username);
			request.setAttribute("message", "请输入验证码！");
			request.getRequestDispatcher("login.html").forward(request, response);
			return;
		}
		HttpSession session = request.getSession(); // 获取session对象
		String code = (String) session.getAttribute("code");
		if(!code.equals(captcha)) {
			request.setAttribute("username", username);
			request.setAttribute("message", "验证码错误！");
			request.getRequestDispatcher("login.html").forward(request, response);
			return;
		}
		BloggerService bloggerService = new BloggerServiceImpl();
		try {
			// 调用服务层进行登录业务处理
			Blogger blogger = bloggerService.login(username, password);
			if (blogger == null) {
				// 未查找到博主信息（登录失败）
				request.setAttribute("username", username);
				request.setAttribute("message", "登录失败！用户名或密码错误！");
				request.getRequestDispatcher("login.html").forward(request, response);
				return;
			} else {
				session.setAttribute("blogger", blogger);
				response.sendRedirect("/MyBlog/index.html");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
